import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @description: 反射 -demo
 * @author: ZM
 * @create: 2021/9/1 14:03
 */
public class ReflectionDemo {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
        Class<Person> personClass = Person.class;
        System.out.println("===========获取修饰符为public的成员变量============");
        Field[] fields1 = personClass.getFields();
        for (Field field : fields1) {
            System.out.println("field.getName() = " + field.getName());
        }
        System.out.println("===========获取指定名称且修饰符为public的成员变量============");
        Field identity = personClass.getField("identity");
        String name1 = identity.getName();
        System.out.println("name1 = " + name1);


        System.out.println("===========获取修饰符为任意的成员变量============");
        Field[] fields = personClass.getDeclaredFields();
        for (Field field : fields) {
            System.out.println("field.getName() = " + field.getName());
        }

        System.out.println("===========获取指定名称且修饰符为任意的成员变量============");
        Field age = personClass.getDeclaredField("age");
        String name = age.getName();
        System.out.println("name = " + name);

        System.out.println("===========反射创建对象============");
        Person person = new Person();
        //获取对象的字节码 3 种方式
        // getClass
        Class<? extends Person> personClass1 = person.getClass();
        Class<? extends Person> personClass2 = person.getClass();
        Class<? extends Person> personClass3 = person.getClass();
        // .class
        Class<Person> personClass4 = Person.class;
        // Class.forName
        Class<?> personClass5 = Class.forName("Person");
        System.out.println("personClass1.hashCode() = " + personClass1.hashCode());
        System.out.println("personClass2.hashCode() = " + personClass2.hashCode());
        System.out.println("personClass3.hashCode() = " + personClass3.hashCode());
        System.out.println("personClass4.hashCode() = " + personClass4.hashCode());
        System.out.println("personClass5.hashCode() = " + personClass5.hashCode());


        // newInstance()
        Person person1 = personClass1.newInstance();
        person1.setAge(22);
        person1.setGender("男");
        person1.setName("王强");
        System.out.println("person1.toString() = " + person1.toString());
        // getConstructor().newInstance()
        Person person2 = personClass4.getConstructor().newInstance();
        person2.setName("王翔");
        person2.setAge(22);
        person2.setGender("男");
        System.out.println("person2.toString() = " + person2.toString());
    }
}
